Ext.namespace('Divo');
Ext.namespace('Divo.app');
Divo.app.checkGrid = Ext.extend(Ext.grid.EditorGridPanel, {
      initComponent : function() {
        var me = this;
        var readerRecord = Ext.data.Record.create([{
              name : "id",
              type : "float"
            }, {
              name : "type",
              type : "string"
            }, {
              name : "materialName",
              type : "string"
            }, {
              name : "spec",
              type : "string"
            }, {
              name : "consum",
              type : "string"
            }, {
              name : "unit",
              type : "string"
            }, {
              name : "price",
              type : "float"
            }, {
              name : "amount",
              type : "float"
            }, {
              name : "managerCode",
              type : "string"
            }]);

        var ds = new Ext.data.Store({
              proxy : new Ext.data.HttpProxy({
                    url : 'ready_code/query_ready_code_edit'
                  }),
              reader : new Ext.data.JsonReader({
                    root : 'rows',
                    totalProperty : 'totalCount',
                    id : 'id'
                  }, readerRecord)
            });
        var cm = new Ext.grid.ColumnModel({
              columns : [{
                    header : '',
                    dataIndex : 'id',
                    hidden : true
                  }, {
                    header : '类别',
                    dataIndex : 'type',
                    width : 100
                  }, {
                    header : '厂家耗材名',
                    dataIndex : 'materialName',
                    width : 100
                  }, {
                    header : '规格',
                    dataIndex : 'spec',
                    width : 100
                  }, {
                    header : '对应消耗品',
                    dataIndex : 'consum',
                    width : 100
                  }, {
                    header : '单位',
                    dataIndex : 'unit',
                    width : 100
                  }, {
                    header : '<font color="blue">单价</font>',
                    dataIndex : 'price',
                    editor : new app.base.NumberField({
                          name : "price",
                          dataIndex : "price",
                          allowBlank : false,
                          width : 100,
                          insert_allowed : true,
                          update_allowed : true
                        })
                  }, {
                    header : '<font color="blue">数量</font>',
                    dataIndex : 'amount',
                    editor : new app.base.NumberField({
                          name : "amount",
                          dataIndex : "amount",
                          allowBlank : false,
                          width : 100,
                          insert_allowed : true,
                          update_allowed : true
                        })
                  }, {
                    header : '管理码',
                    dataIndex : 'managerCode',
                    width : 100
                  }]
            });
        Ext.apply(this, {
              store : ds,
              cm : cm,
              loadMask : true,
              clicksToEdit : 1
            });
        Divo.app.checkGrid.superclass.initComponent.apply(this, arguments);
      },
      onRender : function() {
        Divo.app.checkGrid.superclass.onRender.apply(this, arguments);
      },
      reloadRecords : function() {
        this.getStore().reload();
      }
    });

Divo.app.DiscountPriceList = function() {
  /* ----------------------- private属性 ----------------------- */
  var gridEl = 'DiscountPrice-grid';
  var grid, selModel, toolbar, win;
  var data;
  var sendGrid, pModel;
  var readySendId;
  /* ----------------------- private方法 ----------------------- */
  // 创建列表
  function createGrid() {
    var queryFlds = new Array();
    var searchFlds = new Ext.util.MixedCollection();
    queryFlds.push('name');
    var fldName = new Ext.form.TextField({
          name : 'name',
          id : gridEl + '-name',
          fieldLabel : '名称',
          allowBlank : true,
          width : 100

        });
    searchFlds.add('name', fldName);

    sendGrid = new Divo.Base.GridView({
          remoteSort : true,
          gridId : gridEl + "p",
          entityClassName : 'com.our.sys.project1.entity.ReadySend',
          queryUrl : 'discount_price/query_send',
          specialFields : ["id", "personId", "actionRoom", "num", "tofficesId",
              "docName", "readySendTime", "readySendWho"],
          jsonId : 'id',
          recordPk : ["id"]
        });

    grid = new Divo.app.checkGrid({
          remoteSort : true,
          gridId : gridEl + "check",
          queryFlds : queryFlds,
          searchFlds : searchFlds,
          hasBbar : false,
          jsonId : 'id',
          recordPk : ["id"]
        });

    pModel = sendGrid.getSelectionModel();
    pModel.on('rowselect', onPRowSelect);

    grid.getStore().on('beforeload', function(store, options) {
          store.baseParams.readySendId = readySendId;
        }, this, true);
  }

  // 刷新列表
  function reloadRecords() {
    sendGrid.getStore().reload();
  }

  function onPRowSelect(selModel, rowIndex, record) {
    var data = record.data;
    readySendId = data.id;
    grid.getStore().load();
  }

  // 创建layout
  function createLayout() {
    toolbar = new Ext.Toolbar({
          items : [{
                icon : "resources/img/g_rec_new.png",
                text : "划价",
                id : "tlb_DISCOUNT",
                handler : discount
              }, "-", {
                icon : "resources/img/g_rec_new.png",
                text : "退高值耗材",
                id : "tlb_CANCEL",
                handler : cancel
              }, "-", {
                icon : "resources/img/g_rec_refresh.gif",
                text : "刷新",
                id : "tlb_REFRESH",
                handler : reloadRecords
              }]
        });
    var viewport = new Ext.Viewport({
          layout : 'border',
          items : [{
                layout : 'border',
                region : 'center',
                border : false,
                items : [{
                      layout : 'fit',
                      region : 'north',
                      border : false,
                      items : [toolbar],
                      height : 25
                    }, {
                      layout : 'fit',
                      region : 'center',
                      border : false,
                      items : [sendGrid]
                    }, {
                      layout : 'fit',
                      region : 'south',
                      border : false,
                      items : [grid],
                      height : 200
                    }]
              }]
        });
    viewport.doLayout();
  }

  function discount() {
    // 判断是否已经填写价格和数量
    var sels = sendGrid.getSelectionModel().getSelections();
    if (sels.length <= 0) {
      Ext.Msg.alert('错误', "请选择一条记录！");
      return;
    }
    var gridStore = grid.getStore();
    var allMoney = 0;
    var str;
    for (var i = 0; i < gridStore.getCount(); i++) {
      var record = gridStore.getAt(i);
      var id = record.get("id");
      var price = record.get("price");
      var amount = record.get("amount");
      var money = parseFloat(price) * parseFloat(amount);
      allMoney = parseFloat(allMoney) + parseFloat(money);

      if (str == null) {
        str = id + "," + price + "," + amount;
      } else {
        str = str + "-" + id + "," + price + "," + amount;
      }

      if (amount == 0 || amount == "0" || amount == "" || amount == null) {
        allMoney = 0;
        Ext.Msg.alert('错误', "数量不能为空！");
        return;
      }
      
      if (price == 0 || price == "0" || price == "" || price == null) {
        allMoney = 0;
        Ext.Msg.alert('错误', "单价不能为0！");
        return;
      }
    }
    Ext.Ajax.request({
          params : {
            readySendId : readySendId,
            strs : str,
            allMoney : allMoney
          },
          url : "discount_price/save_discount",
          callback : function(o, s, r) {
            var respText = Ext.decode(r.responseText);
            if (respText.success) {
              sendGrid.getStore().load();
              grid.getStore().load();
            } else {
              if (respText.message.length > 0) {
                this.startEditing(cm.row, cm.column);
                Ext.Msg.alert('错误', respText.message);
              }
            }
          }
        });
  }

  function cancel() {
    // 判断是否选中一条记录
    var sels = sendGrid.getSelectionModel().getSelections();
    if (sels.length <= 0) {
      Ext.Msg.alert('错误', "请选择一条记录！");
      return;
    }
    Ext.Msg.show({
          title : '确认',
          msg : '是否确认?',
          buttons : Ext.Msg.YESNO,
          fn : function(btn) {
            if (btn == 'yes') {
              Ext.Ajax.request({
                    params : {
                      readySendId : readySendId
                    },
                    url : "discount_price/delete_send",
                    callback : function(o, s, r) {
                      var respText = Ext.decode(r.responseText);
                      if (respText.success) {
                        sendGrid.getStore().load();
                        grid.getStore().load();
                      } else {
                        if (respText.message.length > 0) {
                          this.startEditing(cm.row, cm.column);
                          Ext.Msg.alert('错误', respText.message);
                        }
                      }
                    }
                  });
            }
          },
          scope : this,
          icon : Ext.MessageBox.QUESTION
        });
  }

  /* ----------------------- public方法 ----------------------- */
  return {
    /**
     * 初始化
     */
    init : function() {
      createGrid();
      createLayout();
      sendGrid.getStore().load();
    }
  }
}();

Ext.onReady(Divo.app.DiscountPriceList.init, Divo.app.DiscountPriceList, true);